package ru.pb.game.data.xml.parsers;

import java.net.InetSocketAddress;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import ru.pb.game.configs.GameNetworkConfig;
import ru.pb.game.data.xml.holders.IPSystemHolder;
import ru.pb.global.network.IPRange;
import ru.pb.global.xml.parsers.AbstractFileParser;

/**
 * @author Felixx
 */
public final class IPSystemParser extends AbstractFileParser<IPSystemHolder>
{
	private static IPSystemParser _instance;

	public static IPSystemParser getInstance()
	{
		if(_instance == null)
		{
			_instance = new IPSystemParser();
		}
		return _instance;
	}

	public IPSystemParser()
	{
		super("./data/IPSystem/network.xml", IPSystemHolder.getInstance());
	}

	@Override
	protected void readData(Node a)
	{
		if("list".equalsIgnoreCase(a.getNodeName()))
		{
			for(Node sa = a.getFirstChild(); sa != null; sa = sa.getNextSibling())
			{
				if("ip_system".equalsIgnoreCase(sa.getNodeName()))
				{
					for(Node s1 = sa.getFirstChild(); s1 != null; s1 = s1.getNextSibling())
					{
						if("range".equalsIgnoreCase(s1.getNodeName()))
						{

							NamedNodeMap s1M = s1.getAttributes();
							String min = s1M.getNamedItem("min").getNodeValue();
							String max = s1M.getNamedItem("max").getNodeValue();
							String address = s1M.getNamedItem("address").getNodeValue();
							if(address.equalsIgnoreCase("DEFAULT"))
							{
								if(GameNetworkConfig.CLIENT_LISTENER_HOST.equalsIgnoreCase("*"))
								{
									InetSocketAddress addr = new InetSocketAddress(GameNetworkConfig.CLIENT_LISTENER_PORT);
									address = addr.getHostName();
								}
								else
									address = GameNetworkConfig.CLIENT_LISTENER_HOST;
							}
							if(DEBUG)
							{
								info(min + "|" + max + "|" + address);
							}
							getHolder().add(new IPRange(min, max, address));
						}
					}
				}
			}
		}
	}
}
